package com.example.totalfinder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

	View top, center_search, center_favorite, center_list, center_setting,
			bottom, center_search_top;
	ListView lv1;
	TextView searchTxt;
	Button but1, but2, but3, but4, but5;

	ArrayAdapter<String> listUrl_adapter = null;

	public static String siteName;
	public static String categoryName;
	public static String searchName;
	ProgressBar loadingBar; // 나중에 구현

	// String Save_Path = "/mnt/Sdcard/Download";
	String Save_Path = "/data/data/com.example.totalfinder/file";
	String File_Name = "";
	String File_Extend = "torrent";
	String FileUrl = "";
	DownloadThread dThread;

	Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		lv1 = (ListView) findViewById(R.id.list_view1);
		searchTxt = (TextView) findViewById(R.id.searchTxt);

		Spinner spinner1;
		//spinner1 = (Spinner) findViewById(R.id.spinner1);

		final Spinner spinner2;
		//spinner2 = (Spinner) findViewById(R.id.spinner2);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.sites, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter
				.createFromResource(this, R.array.categories1,
						android.R.layout.simple_spinner_item);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final ArrayAdapter<CharSequence> adapter2 = ArrayAdapter
				.createFromResource(this, R.array.categories2,
						android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final ArrayAdapter<CharSequence> adapter3 = ArrayAdapter
				.createFromResource(this, R.array.categories3,
						android.R.layout.simple_spinner_item);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//		spinner1.setAdapter(adapter);
//		spinner1.setPrompt("원하는 사이트를 선택하세요.");

		//spinner2.setPrompt("원하는 분류를 선택하세요.");
		siteName = "http://torrentgun.net/bbs/";
		//spinner2.setAdapter(adapter1);	
		
		
		
//		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			public void onItemSelected(AdapterView<?> parent, View v,
//					int position, long id) {
//				switch (position) {
//				case 0:
//					siteName = "http://www.torrentrg.com/bbs/board.php?bo_table=";
//					spinner2.setAdapter(adapter1);
//					break;
//				case 1:
//					siteName = "http://job.etorrent.co.kr/bbs/board.php?bo_table=";
//					spinner2.setAdapter(adapter2);
//					break;
//				case 2:
//					siteName = "http://vtorrent.co.kr/main/storage.php?section=";
//					spinner2.setAdapter(adapter3);
//					break;
//				}
//
//			}
//
//			public void onNothingSelected(AdapterView<?> parent) {
//
//			}
//
//		});



		top = findViewById(R.id.top_contents);
		center_search = findViewById(R.id.search_contents);
		center_favorite = findViewById(R.id.favorite_contents);
		center_list = findViewById(R.id.list_contents);
		center_setting = findViewById(R.id.setting_contents);
		bottom = findViewById(R.id.bottom_contents);
		center_search_top = findViewById(R.id.search_top);

		but1 = (Button) findViewById(R.id.Button1);
		but1.setOnClickListener(mClickListener);

		but2 = (Button) findViewById(R.id.Button2);
		but2.setOnClickListener(mClickListener);

		but3 = (Button) findViewById(R.id.Button3);
		but3.setOnClickListener(mClickListener);

		but4 = (Button) findViewById(R.id.Button4);
		but4.setOnClickListener(mClickListener);

		but5 = (Button) findViewById(R.id.searchBtn);
		but5.setOnTouchListener(mTouchListener);

		but5.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				TextView searchTxt = (TextView) findViewById(R.id.searchTxt);

//				if (spinner2.getAdapter() == adapter1) {
//					 String urlStr = searchTxt.getText().toString();
					try {
//						searchName = "&q=&k="
//								+ java.net.URLEncoder.encode(searchTxt
//										.getText().toString(), "euc-KR");
						searchName = "s.php?q=&k="  + java.net.URLEncoder.encode(searchTxt
								.getText().toString(), "euc-KR");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//				}
				//String urlStr = siteName + categoryName + searchName;
				String urlStr = siteName + searchName;
				
				ConnectThread thread1 = new ConnectThread(urlStr);
				thread1.start();

				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchTxt.getWindowToken(), 0);
			}
		});

		lv1.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					final int position, long id) {

				final CharSequence[] torrentSmi = { "$토렌트파일", "$자막파일" };
				final AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);

				builder.setTitle("다운받기");
				builder.setItems(torrentSmi,
						new DialogInterface.OnClickListener() {

							@SuppressLint("NewApi")
							@Override
							public void onClick(DialogInterface dialog, int item) {
								// TODO
								// Auto-generated
								// method stub

								// String no = String
								// .valueOf(item); // 0
								// 이면
								// torrent,
								// 1이면
								// smi

								ConnectThread2 thread2 = new ConnectThread2(
										listUrl_adapter.getItem(position),
										String.valueOf(item));
								thread2.start();

								// else
								// {
								//
								// showDownloadFile();
								// }

							} // onclick

							// private void
							// showDownloadFile() {
							// // TODO
							// Auto-generated method
							// stub
							// Intent intent = new
							// Intent();
							// intent.setAction(android.content.Intent.ACTION_VIEW);
							// File file = new
							// File(Save_Path + "/"
							// + File_Name);
							//
							// }
						});
				AlertDialog alert = builder.create();
				alert.show();
			}// onItemClick

		});

	}

	Button.OnClickListener mClickListener = new Button.OnClickListener() {

		public void onClick(View v) {

			switch (v.getId()) {

			case R.id.Button1:

				ChangePage(1);

				break;

			case R.id.Button2:

				ChangePage(2);

				break;

			case R.id.Button3:

				ChangePage(3);

				break;

			case R.id.Button4:

				ChangePage(4);

				break;

			}

		}

	};

	Button.OnTouchListener mTouchListener = new Button.OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (v.getId()) {

			case R.id.searchBtn:

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					but5.setBackgroundColor(Color.parseColor("#fdf9c3"));
					but5.setTextColor(Color.parseColor("#00622e"));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					but5.setBackgroundColor(Color.parseColor("#00622e"));
					but5.setTextColor(Color.parseColor("#fdf9c3"));
				}

				break;
			}

			return false;

		}
	};

	void ChangePage(int page) {

		center_search.setVisibility(View.INVISIBLE);
		center_favorite.setVisibility(View.INVISIBLE);
		center_list.setVisibility(View.INVISIBLE);
		center_setting.setVisibility(View.INVISIBLE);

		switch (page) {

		case 1:
			changeColor(center_search, "#fdf9c3", "#00622e", "#00622e",
					"#fdf9c3", "#00622e", "#fdf9c3", "#00622e", "#fdf9c3");
			break;

		case 2:
			changeColor(center_favorite, "#00622e", "#fdf9c3", "#fdf9c3",
					"#00622e", "#00622e", "#fdf9c3", "#00622e", "#fdf9c3");
			break;

		case 3:
			changeColor(center_list, "#00622e", "#fdf9c3", "#00622e",
					"#fdf9c3", "#fdf9c3", "#00622e", "#00622e", "#fdf9c3");
			break;

		case 4:
			changeColor(center_setting, "#00622e", "#fdf9c3", "#00622e",
					"#fdf9c3", "#00622e", "#fdf9c3", "#fdf9c3", "#00622e");
			break;

		}

	}

	public void changeColor(View target, String color1, String color2,
			String color3, String color4, String color5, String color6,
			String color7, String color8) {
		target.setVisibility(View.VISIBLE);
		but1.setBackgroundColor(Color.parseColor(color1));
		but1.setTextColor(Color.parseColor(color2));
		but2.setBackgroundColor(Color.parseColor(color3));
		but2.setTextColor(Color.parseColor(color4));
		but3.setBackgroundColor(Color.parseColor(color5));
		but3.setTextColor(Color.parseColor(color6));
		but4.setBackgroundColor(Color.parseColor(color7));
		but4.setTextColor(Color.parseColor(color8));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
	class ConnectThread extends Thread {

		String urlStr;

		ListView lv1 = (ListView) findViewById(R.id.list_view1);
		TextView searchTxt = (TextView) findViewById(R.id.searchTxt);

		public ConnectThread(String inStr) {
			urlStr = inStr;
		}

		public void run() {

			try {
				final String output = request(urlStr);
				final StringTokenizer st = new StringTokenizer(output, "\n");

				String temp_output = null;
				ArrayList<String> list_array = new ArrayList<String>();
				ArrayList<String> list_array_url = new ArrayList<String>();

				if (output.isEmpty()) {
					list_array.add("No Data");
				} else {
					while (st.hasMoreTokens()) {
						temp_output = st.nextToken();
						if (temp_output.contains("http")) {

							// Toast.makeText(getApplicationContext(),
							// temp_output, Toast.LENGTH_LONG).show();
							list_array_url.add(temp_output);
							listUrl_adapter = new ArrayAdapter<String>(
									MainActivity.this, R.layout.search_result,
									list_array_url);

						} else {
							list_array.add(temp_output);
						}
					}
				}

				final ArrayAdapter<String> list_adapter = new ArrayAdapter<String>(
						MainActivity.this, R.layout.search_result, list_array);

				handler.post(new Runnable() {
					public void run() {
						lv1.setAdapter(list_adapter);
					}
				});

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private String request(String urlStr) {
			
			System.out.println("urlStr : " + urlStr);
			
			StringBuilder output = new StringBuilder();
			String temp = searchTxt.getText().toString();
			String temp1, temp2, temp3;
			try {
				int counter = 0;
				int startAt, endAt, startAt_2, endAt_2;
				URL url = new URL(urlStr);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				if (conn != null) {

					conn.setConnectTimeout(10000);
					conn.setRequestMethod("GET");
					conn.setDoInput(true);
					conn.setDoOutput(true);

					int resCode = conn.getResponseCode();
					if (resCode == HttpURLConnection.HTTP_OK) {

						BufferedReader reader = new BufferedReader(
								new InputStreamReader(conn.getInputStream(),
										"utf-8"));
						String line = null;
						while (true) {

							line = reader.readLine();
							if (line == null) {
								break;
							}
							if (line.contains("제&nbsp;&nbsp;&nbsp;목")) {
								counter = 1;
							}

							if (line.contains("</div>")) {
								counter = 0;
							}
							
							if ((counter == 1) && (line.contains("&k="+temp))) {
					
								temp1 = null;
								temp2 = null;
								temp3 = null;
								startAt = line.indexOf("a href='");
								endAt = line.indexOf("page='>");
								output.append("http://www.torrentgun.net/bbs/"
										+ line.subSequence(startAt + 7, endAt)
										 + "\n");
								temp1=reader.readLine();
								temp2=reader.readLine();
								
								endAt_2=temp2.indexOf("</a> </td>");
								output.append(temp2.subSequence(0, endAt_2).toString().trim()+"\n");
//								startAt = line.indexOf("<span>");
//								temp1 = line.substring(startAt + 6);
//								endAt = temp1.indexOf("<span");
//								output.append(temp1.subSequence(0, endAt));
//								endAt = temp1.indexOf(">");
//								temp2 = temp1.substring(endAt + 1);
//								endAt = temp2.indexOf("</span>");
//								output.append(temp2.substring(0, endAt));
//								temp3 = temp2.substring(endAt + 7);
//								endAt = temp3.indexOf("</span>");
//								output.append(temp3.substring(0, endAt) + "\n");
//								counter = 0;
							}
							if (line.contains("계속검색")) {
								output.append("계속 검색\n");
								startAt = line.indexOf("<a href");
								temp1 = line.substring(startAt + 10);
								endAt = temp1.indexOf("'");
								output.append("http://www.torrentrg.com/bbs"
										+ temp1.subSequence(0, endAt) + "\n");
							}
						}
						reader.close();
						conn.disconnect();
					}
				}

			} catch (Exception e) {
				Log.e("SampleHttp", "Exception in processing response", e);

			}// catch
			
			System.out.print(output.toString());
			return output.toString();
		}// request()

	} // ConnectThread

	class ConnectThread2 extends Thread {

		String urlStr1;
		String no1;

		ListView lv1 = (ListView) findViewById(R.id.list_view1);
		TextView searchTxt = (TextView) findViewById(R.id.searchTxt);

		public ConnectThread2(String urlStr, String no) {
			urlStr1 = urlStr;
			no1 = no;
		}

		public void run() {

			try {

				String temp_output_2 = request_2(urlStr1, no1); // 다운경로
				// 받아오기
				StringTokenizer st_2 = new StringTokenizer(temp_output_2, "\n");
				if (temp_output_2.isEmpty()) {
					Toast.makeText(getApplicationContext(), "no data",
							Toast.LENGTH_LONG).show();

				} else {
					while (st_2.hasMoreTokens()) {
						FileUrl = st_2.nextToken();
						handler.post(new Runnable() {
							public void run() {
								Toast.makeText(getApplicationContext(),
										"FileUrl : " + FileUrl,
										Toast.LENGTH_LONG).show();
							}
						});

						File_Name = st_2.nextToken();
						handler.post(new Runnable() {
							public void run() {
								Toast.makeText(getApplicationContext(),
										"File_Name : " + File_Name,
										Toast.LENGTH_LONG).show();
							}
						});
						// Toast.makeText(getApplicationContext(),
						// "File_Name : "
						// +
						// File_Name,
						// Toast.LENGTH_LONG).show();

						File dir = new File(Save_Path);
						if (!dir.exists()) {
							dir.mkdir();
						}
						// 경로에 파일이
						// 없으면 다운실행
						if (new File(Save_Path + "/" + File_Name).exists() == false) {

							// loadingBar.setVisibility(View.VISIBLE);
							downloadFile(FileUrl, Save_Path + "/" + File_Name);
							// dThread
							// = new
							// DownloadThread(FileUrl,
							// Save_Path
							// + "/"
							// +
							// File_Name);
							// dThread.start();
						}

					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private void downloadFile(String serverPath, String localPath) {

			final String ServerUrl = serverPath;
			String LocalPath = localPath;
			InputStream is = null;
			FileOutputStream fos = null;
			HttpURLConnection conn = null;
			int read;
			try {

				// is = new URL(ServerUrl).openStream();
				// File file = new File(LocalPath);
				// fos = openFileOutput(file,MODE_WORLD_READABLE);
				// while((read=is.read(buffer)) != -1){
				// fos.write(buffer, 0, read);
				//
				// fos.flush();
				// }
				URL downloadUrl = new URL(ServerUrl);

				conn = (HttpURLConnection) downloadUrl.openConnection();

				if (conn != null) {
					conn.setDoInput(true);
					conn.setDoOutput(true);
					conn.connect();

					int resCode = conn.getResponseCode();
					if (resCode == HttpURLConnection.HTTP_OK) {

						/*
						final String sdcard = Environment
								.getExternalStorageDirectory()
								.getAbsolutePath();
						handler.post(new Runnable() {
							public void run() {
								Toast.makeText(getApplicationContext(),
										"sdcard경로 : " + sdcard,
										Toast.LENGTH_LONG).show();
							}
						});
						*/

						is = new URL(ServerUrl).openStream();
						int len = conn.getContentLength();
						byte[] buffer = new byte[4096];

						File file = new File(LocalPath);
						fos = new FileOutputStream(file);

						while ((read = is.read(buffer)) != -1) {
							if (len > 0) {
								fos.write(buffer, 0, read);
							}
						}
						handler.post(new Runnable() {
							public void run() {
								Toast.makeText(getApplicationContext(),
										"download complete", Toast.LENGTH_LONG)
										.show();
							}
						});
					}
				}

			} catch (MalformedURLException e) {
				Log.e("error01", e.getMessage());

			} catch (IOException e) {
				Log.e("error02", e.getMessage());
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (fos != null) {
						fos.close();
					}
				} catch (IOException e) {

				}

				if (conn != null) {
					conn.disconnect();
				}

			}

		}

		private String request_2(String urlStr, String no) {
			final StringBuilder output_2 = new StringBuilder();

			// Toast.makeText(getApplicationContext(), urlStr,
			// Toast.LENGTH_LONG).show();

			try {
				int counter = 0;
				int startAt, endAt;
				int fileNameStartAt = 0, fileNameEndAt = 0;
				String temp1;
				URL url = new URL(urlStr);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				if (conn != null) {

					conn.setConnectTimeout(10000);
					conn.setRequestMethod("GET");
					conn.setDoInput(true);
					conn.setDoOutput(true);

					int resCode = conn.getResponseCode();
					if (resCode == HttpURLConnection.HTTP_OK) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));

						String line = null;
						while (true) {
							line = reader.readLine();
							if (line == null) {
								// Toast.makeText(getApplicationContext(),
								// "line end", Toast.LENGTH_LONG).show();
								break;
							}
							if (line.contains("javascript:ile_dwnload2")) {
								counter = 1;
							}

							if (no.equals("0")) {
								if ((counter == 1) && (line.contains("'0');"))) {
									temp1 = null;
									startAt = line.indexOf("wr_id");
									endAt = line.indexOf("&no");
									output_2.append("http://www.torrentrg.com/bbs/download.php?bo_table="
											+ categoryName
											+ "&wr_id="
											+ line.subSequence(startAt + 6,
													endAt)
											+ "&no="
											+ no
											+ "&sca=&sfl=wr_subject&stx="
											+ searchTxt.getText()
											+ "&sop=and"
											+ "\n");

									fileNameStartAt = line.indexOf("and' ,  ");
									temp1 = line.substring(fileNameStartAt + 8);
									fileNameEndAt = temp1.indexOf("',  '0'");
									output_2.append(temp1.subSequence(1,
											fileNameEndAt));
									counter = 0;

								}
							}

							if (no.equals("1")) {

								if (line.contains("javascript:ile_dwnload2")) {
									counter = 1;
								}

								if ((counter == 1) && (line.contains("'1');"))) {

									temp1 = null;
									startAt = line.indexOf("wr_id");
									endAt = line.indexOf("&no");
									output_2.append("http://www.torrentrg.com/bbs/download.php?bo_table="
											+ categoryName
											+ "&wr_id="
											+ line.subSequence(startAt + 6,
													endAt)
											+ "&no="
											+ no
											+ "&sca=&sfl=wr_subject&stx="
											+ searchTxt.getText()
											+ "&sop=and"
											+ "\n");

									fileNameStartAt = line.indexOf("and' ,  ");
									temp1 = line.substring(fileNameStartAt + 8);
									fileNameEndAt = temp1.indexOf("',  '1'");
									output_2.append(temp1.subSequence(1,
											fileNameEndAt));
									counter = 0;

								}
							}
							// if (line.contains("javascript:file_download")) {
							// counter = 1;
							// }
							//
							// if ((counter == 1)) {
							// temp1 = null;
							// startAt = line.indexOf("wr_id");
							// endAt = line.indexOf("&no");
							// output_2.append("http://www.torrentrg.com/bbs/download.php?bo_table="
							// + categoryName
							// + "&wr_id="
							// + line.subSequence(startAt + 6, endAt)
							// +"&no="
							// + no
							// + "&sca=&sfl=wr_subject&stx="
							// + searchTxt.getText()
							// + "&sop=and" + "\n");
							//
							// fileNameStartAt = line.indexOf("and', ");
							// temp1 = line.substring(fileNameStartAt+6);
							//
							// if(no.equals("0")){
							// fileNameEndAt = temp1.indexOf("', '0'");
							// }
							// if (no.equals("1")){
							// fileNameEndAt = temp1.indexOf("', '1'");
							// }
							//
							// output_2.append(temp1.subSequence(1,fileNameEndAt));
							//
							// Toast.makeText(getApplicationContext(), output_2,
							// Toast.LENGTH_LONG).show();
							// counter = 0;
							// }

						} // while
						reader.close();
						conn.disconnect();

					}
				}

			} catch (Exception e) {
				Log.e("SampleHttp", "Exception in processing response", e);

			}// catch

			return output_2.toString();

		}// request_2

	} // ConnectThread2

	class DownloadThread extends Thread {
		String ServerUrl;
		String LocalPath;

		DownloadThread(String serverPath, String localPath) {
			ServerUrl = serverPath;
			LocalPath = localPath;
		}

		public void run() {
			int read;

			try {

				// Toast.makeText(getApplicationContext(), "여기1",
				// Toast.LENGTH_LONG).show();
				URL downloadUrl = new URL(ServerUrl);
				HttpURLConnection conn = (HttpURLConnection) downloadUrl
						.openConnection();
				int len = conn.getContentLength();
				byte[] buffer = new byte[len];
				InputStream is = conn.getInputStream();
				File file = new File(LocalPath);
				FileOutputStream fos = new FileOutputStream(file);
				for (;;) {
					// Toast.makeText(getApplicationContext(), "여기2",
					// Toast.LENGTH_LONG).show();
					read = is.read(buffer);
					if (read <= 0) {
						break;
					}
					fos.write(buffer, 0, read);
				}
				is.close();
				fos.close();
				conn.disconnect();

			} catch (MalformedURLException e) {
				Log.e("error01", e.getMessage());

			} catch (IOException e) {
				Log.e("error02", e.getMessage());
			}
			// mAfterDown.
		}

		Handler mAfterDown = new Handler() {

			public void handleMessage(Message msg) {

				// loadingBar.setVisibility(View.GONE);
				showDownloadFile();
			}
		};

		private void showDownloadFile() {

			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			File file = new File(Save_Path + "/" + File_Name);

			// if(File_Extend.equals("torrent"))
		}
	} // DownloadThread

}
